package pcb.views.library 
{
	import com.intel.utils.Debugger;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.utils.Timer;
	import pcb.views.uievents.SlideEvent;
	import pcb.models.vo.Interaction;
	import pcb.views.library.AnnotationMC;
	
	/**
	 * ...
	 * @author ...
	 */
	public class Click extends MovieClip
	{
		//.5 sec delay on complete show me
		private var delay:Number = 500;

		public function Click() 
		{
			this.mouseChildren = false;
			this.buttonMode = true;
			this.useHandCursor = true;
			
			var sm:MovieClip = this.parent.getChildByName("mcShowMe") as MovieClip;
			trace("sm " + sm);
			if (sm != null) {
				sm.visible = false;
			}
			
			createEventHandler();
			
			dispatchEvent(new Event(SlideEvent.INTERACTIVITY_CREATED, true));
			
		}
		
		internal function createEventHandler():void 
		{
			this.addEventListener(MouseEvent.CLICK, clicked);
			this.addEventListener(Event.REMOVED, removed);
		}
		
		internal function removeListeners():void 
		{
			if (this.hasEventListener(MouseEvent.CLICK)) {
				this.removeEventListener(MouseEvent.CLICK, clicked);
			}
		}
		
		private function removed(e:Event):void 
		{
			removeListeners();
			this.removeEventListener(Event.REMOVED, removed);
		}
		
		public function clicked(e:MouseEvent):void {			
			removeListeners();
			dispatchEvent(new Event(SlideEvent.INTERACTIVITY_COMPLETED, true));
		}
		
		public function addAnnotation(mcAnnotation:AnnotationMC):void 
		{			
			mcAnnotation.name = "mcAnnotation";
			this.parent.addChild(mcAnnotation);
		}
		
		public function getAnnotationMcPosition():DisplayObject {
			return this as DisplayObject;
		}
		
		public function showMe():void 
		{
			removeListeners();
			var sm:MovieClip = this.parent.getChildByName("mcShowMe") as MovieClip;
			trace("sm " + sm);
			if (sm != null) {
				if (this.parent.getChildByName("mcAnnotation")) {
					this.parent.removeChild(this.parent.getChildByName("mcAnnotation"));
				}
				sm.visible = true;
				sm.play();
				sm.addEventListener(Event.ENTER_FRAME, showMeEnterFrame);
			} else {
				Debugger.traceOut("could not find show me MC", Debugger.ERROR);
			}
			
		}
		
		private function showMeEnterFrame(e:Event):void 
		{
			var mc:MovieClip = e.target as MovieClip;
			if (mc.currentFrame == mc.totalFrames) {
				var timer:Timer = new Timer(delay,1);
				timer.addEventListener(TimerEvent.TIMER_COMPLETE, t_onComplete);				
				timer.start();
				mc.removeEventListener(Event.ENTER_FRAME, showMeEnterFrame);
			}
			mc = null;
		}
		
		private function t_onComplete(e:TimerEvent):void 
		{
			e.target.removeEventListener(TimerEvent.TIMER_COMPLETE, t_onComplete);
			dispatchEvent(new Event(SlideEvent.INTERACTIVITY_COMPLETED, true));
		}
		
	}
	
}